# 数据处理层：实现连接数据库，写数据库，读数据库
import pymysql

host = 'localhost'
port = 3306
user = 'root'
password = 'root'
database = 'test'
charset = 'utf8'


def get_conn():
    db = pymysql.Connect(host=host, port=port, user=user, password=password)
    return db


def read_data(sql):
    db = get_conn()
    cursor = db.cursor()
    data = None
    try:
        cursor.execute(sql)
        data = cursor.fetchall()
    except Exception as e:
        print(e)
    cursor.close()
    db.close()
    return data


def write_data(sql):
    db = get_conn()
    cursor = db.cursor()
    rows = 0
    try:
        rows = cursor.execute(sql)
        db.commit()
    except Exception as e:
        db.rollback()
        print(e)

    cursor.close()
    db.close()
    return rows


if __name__ == '__main__':
    sql = 'update users set password = "123456"'
    print(write_data(sql))
